package com.pinyougou.sellergoods.service.impl;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.pinyougou.mapper.*;
import com.pinyougou.pojo.*;
import com.pinyougou.pojogroup.GoodsAndDesc;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.PageHelper;
import com.pinyougou.pojo.TbGoodsExample.Criteria;
import com.pinyougou.sellergoods.service.GoodsService;


/**
 * 服务实现层
 * @author Administrator
 *
 */
@Service
public class GoodsServiceImpl implements GoodsService {

	@Autowired
	private TbGoodsMapper goodsMapper;

	@Autowired
	private TbGoodsDescMapper goodsDescMapper;

	@Autowired
	private TbBrandMapper brandMapper;

	@Autowired
	private TbItemMapper itemMapper;

	@Autowired
	private TbItemCatMapper itemCatMapper;

	@Autowired
	private TbSellerMapper sellerMapper;
	/**
	 * 查询全部
	 */
	@Override
	public List<TbGoods> findAll() {
		return goodsMapper.selectByExample(null);
	}

	/**
	 * 按分页查询
	 */
//	@Override
//	public PageInfo<TbGoods> findPage(int pageNum, int pageSize) {
//		PageHelper.startPage(pageNum, pageSize);
//		List<TbGoods> list = goodsMapper.selectByExample(null);
//		PageInfo<TbGoods> info = new PageInfo<TbGoods>(list);
//		return info;
//	}

	/**
	 * 商品录入,添加商品
	 * @param goodsAndDesc
	 */
	@Override
	public void add(GoodsAndDesc goodsAndDesc) {

		goodsAndDesc.getGoods().setAuditStatus("0"); //设置未申请状态
		goodsMapper.insert(goodsAndDesc.getGoods()); //插入商品
		goodsAndDesc.getGoodsDesc().setGoodsId(goodsAndDesc.getGoods().getId());//设置商品扩展id=商品id
		goodsDescMapper.insert(goodsAndDesc.getGoodsDesc()); //插入商品扩展信息

		//插入商品规格SKU列表数据
		if ("1".equals(goodsAndDesc.getGoods().getIsEnableSpec())){ //如果启用规格
			for(TbItem item :goodsAndDesc.getItemList()){
				//标题
				String title= goodsAndDesc.getGoods().getGoodsName();
				Map<String,Object> specMap = JSON.parseObject(item.getSpec());
				for(String key:specMap.keySet()){
					title +=" "+ specMap.get(key);
				}
				item.setTitle(title);

				setItemValues(goodsAndDesc,item);
				itemMapper.insert(item);
			}
		}else { //如果不启用规格
			TbItem item=new TbItem();
			item.setTitle(goodsAndDesc.getGoods().getGoodsName());//商品KPU+规格描述串作为SKU名称
			item.setPrice( goodsAndDesc.getGoods().getPrice() );//价格
			item.setStatus("1");//状态
			item.setIsDefault("1");//是否默认
			item.setNum(9999);//库存数量
			item.setSpec("{}");

			setItemValues(goodsAndDesc,item);
			itemMapper.insert(item);

		}

	}


	/**
	 * 插入SKU列表,前台读取
	 * @param goodsAndDesc
	 * @param item
	 */
	private void setItemValues(GoodsAndDesc goodsAndDesc,TbItem item){

		item.setGoodsId(goodsAndDesc.getGoods().getId());//商品SPU编号
		item.setSellerId(goodsAndDesc.getGoods().getSellerId());//商家编号
		item.setCategoryid(goodsAndDesc.getGoods().getCategory3Id());//商品分类编号（3级）
		item.setCreateTime(new Date());//创建日期
		item.setUpdateTime(new Date());//修改日期
		//品牌名称
		TbBrand brand = brandMapper.selectByPrimaryKey(goodsAndDesc.getGoods().getBrandId());
		item.setBrand(brand.getName());
		//分类名称
		TbItemCat itemCat = itemCatMapper.selectByPrimaryKey(goodsAndDesc.getGoods().getCategory3Id());
		item.setCategory(itemCat.getName());
		//商家名称
		TbSeller seller = sellerMapper.selectByPrimaryKey(goodsAndDesc.getGoods().getSellerId());
		item.setSeller(seller.getNickName());
		//图片地址（取spu的第一个图片）
		List<Map> imageList = JSON.parseArray(goodsAndDesc.getGoodsDesc().getItemImages(), Map.class) ;
		if(imageList.size()>0){
			item.setImage ( (String)imageList.get(0).get("url"));
		}
	}

	
	/**
	 * 修改
	 */
	@Override
	public void update(GoodsAndDesc goodsAndDesc){
		//更新基本属性表
		goodsMapper.updateByPrimaryKey(goodsAndDesc.getGoods());
		//更新扩展属性表
		goodsDescMapper.updateByPrimaryKey(goodsAndDesc.getGoodsDesc());
		//删除原有的SKU列表数据
		TbItemExample example=new TbItemExample();
		TbItemExample.Criteria criteria = example.createCriteria();
		criteria.andGoodsIdEqualTo(goodsAndDesc.getGoods().getId());
		itemMapper.deleteByExample(example);

		//插入修改后的SKU列表数据
		if ("1".equals(goodsAndDesc.getGoods().getIsEnableSpec())){ //如果启用规格
			for(TbItem item :goodsAndDesc.getItemList()){
				//标题
				String title= goodsAndDesc.getGoods().getGoodsName();
				Map<String,Object> specMap = JSON.parseObject(item.getSpec());
				for(String key:specMap.keySet()){
					title +=" "+ specMap.get(key);
				}
				item.setTitle(title);

				setItemValues(goodsAndDesc,item);
				itemMapper.insert(item);
			}
		}else { //如果不启用规格
			TbItem item=new TbItem();
			item.setTitle(goodsAndDesc.getGoods().getGoodsName());//商品KPU+规格描述串作为SKU名称
			item.setPrice( goodsAndDesc.getGoods().getPrice() );//价格
			item.setStatus("1");//状态
			item.setIsDefault("1");//是否默认
			item.setNum(9999);//库存数量
			item.setSpec("{}");

			setItemValues(goodsAndDesc,item);
			itemMapper.insert(item);

		}
	}	
	
	/**
	 * 根据goodsId获取实体
	 * @param id
	 * @return
	 */
	@Override
	public GoodsAndDesc findOne(Long id){

		GoodsAndDesc goodsAndDesc = new GoodsAndDesc();
		//设置goods商品基本基本表
		TbGoods tbGoods = goodsMapper.selectByPrimaryKey(id);
		goodsAndDesc.setGoods(tbGoods);
		//设置goodDesc商品扩展表
		TbGoodsDesc tbGoodsDesc = goodsDescMapper.selectByPrimaryKey(id);
		goodsAndDesc.setGoodsDesc(tbGoodsDesc);

		//设置itemList商品SKU列表
		TbItemExample example = new TbItemExample();
		TbItemExample.Criteria criteria = example.createCriteria();
		criteria.andGoodsIdEqualTo(id);
		List<TbItem> itemList = itemMapper.selectByExample(example);

		goodsAndDesc.setItemList(itemList);
		return goodsAndDesc;
	}

	/**
	 * 批量删除
	 */
	@Override
	public void delete(Long[] ids) {
		for(Long id:ids){
			TbGoods tbGoods = goodsMapper.selectByPrimaryKey(id);
			tbGoods.setIsDelete("1");

			goodsMapper.updateByPrimaryKey(tbGoods);
		}		
	}
	
	
	@Override
	public PageInfo<TbGoods> findPage(TbGoods goods, int pageNum, int pageSize) {
		PageHelper.startPage(pageNum, pageSize);
		
		TbGoodsExample example=new TbGoodsExample();
		Criteria criteria = example.createCriteria();

		criteria.andIsDeleteIsNull();//非删除状态
		if(goods!=null){			
						if(goods.getSellerId()!=null && goods.getSellerId().length()>0){
				criteria.andSellerIdEqualTo(goods.getSellerId());
			}
			if(goods.getGoodsName()!=null && goods.getGoodsName().length()>0){
				criteria.andGoodsNameLike("%"+goods.getGoodsName()+"%");
			}
			if(goods.getAuditStatus()!=null && goods.getAuditStatus().length()>0){
				criteria.andAuditStatusLike("%"+goods.getAuditStatus()+"%");
			}
			if(goods.getIsMarketable()!=null && goods.getIsMarketable().length()>0){
				criteria.andIsMarketableLike("%"+goods.getIsMarketable()+"%");
			}
			if(goods.getCaption()!=null && goods.getCaption().length()>0){
				criteria.andCaptionLike("%"+goods.getCaption()+"%");
			}
			if(goods.getSmallPic()!=null && goods.getSmallPic().length()>0){
				criteria.andSmallPicLike("%"+goods.getSmallPic()+"%");
			}
			if(goods.getIsEnableSpec()!=null && goods.getIsEnableSpec().length()>0){
				criteria.andIsEnableSpecLike("%"+goods.getIsEnableSpec()+"%");
			}
			if(goods.getIsDelete()!=null && goods.getIsDelete().length()>0){
				criteria.andIsDeleteLike("%"+goods.getIsDelete()+"%");
			}
	
		}

		List<TbGoods> list = goodsMapper.selectByExample(example);
		PageInfo<TbGoods> info = new PageInfo<TbGoods>(list);
		return info;
	}

	/**
	 * 批量修改商品审核状态
	 * @param ids
	 * @param status
	 */
	@Override
	public void updateStatus(Long[] ids, String status) {
		for (Long id : ids) {
			TbGoods tbGoods = goodsMapper.selectByPrimaryKey(id);
			tbGoods.setAuditStatus(status);
			goodsMapper.updateByPrimaryKey(tbGoods);
		}
	}

	/**
	 * 更新索引库
	 * 根据商品id和状态查询item表信息
	 * @param goodsIds
	 * @param status
	 * @return
	 */
	@Override
	public List<TbItem> findItemListByGoodsIdandStatus(Long[] goodsIds, String status) {
		TbItemExample example=new TbItemExample();
		TbItemExample.Criteria criteria = example.createCriteria();
		criteria.andGoodsIdIn(Arrays.asList(goodsIds));
		criteria.andStatusEqualTo(status);
		return itemMapper.selectByExample(example);
	}

}
